package com.itheima.websocket.server;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;


import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Class: WebSocketServer
 * @Package com.itheima.websocket.config.server
 * @Description: 创建WebServer核心类，用于连接、消息的管理
 * @Company: http://www.itheima.com/
 */
@ServerEndpoint("/ws/{userId}")
@Component
public class WebSocketServer {
    //日志
    static Log log = LogFactory.getLog(WebSocketServer.class);
    //在线数量
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    //并发map，用于存储客户端socket
    private static Map<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    //会话信息
    private Session session;
    //接收
    private String userId = "";

    /*
     * @Description:  客户端建立websocket连接
     * @Method: onOpen
     * @Param: [session, userId]
     * @Update:
     * @since: 1.0.0
     * @Return: void
     *
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }

        try {
            sendMessage("Server>>>远程WebSocket连接成功");
            log.info("用户" + userId + "成功连接,当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("创建连接发生异常");
        }
    }

    /*
     * @Description: 连接关闭
     * @Method: onClose
     * @Param: []
     * @Update:
     * @since: 1.0.0
     * @Return: void
     *
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /*
     * @Description: 消息处理器（中转）
     * @Method: onMessage
     * @Param: [message, session]
     * @Update:
     * @since: 1.0.0
     * @Return: void
     *
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (StringUtils.isNotEmpty(message)) {
            try {
                //解析消息
                JSONObject jsonObject = JSON.parseObject(message);
                String toUserId = jsonObject.getString("toUserId");
                String msg = jsonObject.getString("msg");
                if (StringUtils.isNotEmpty(toUserId) && webSocketMap.containsKey(toUserId)) {
                    //消息中转
                    webSocketMap.get(toUserId).sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * @Description: 错误处理
     * @Method: onError
     * @Param: [session, error]
     * @Update:
     * @since: 1.0.0
     * @Return: void
     *
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /*
     * @Description: 获取在线人数
     * @Method: getOnlineCount
     * @Param: []
     * @Update:
     * @since: 1.0.0
     * @Return: java.util.concurrent.atomic.AtomicInteger
     *
     */
    public static synchronized AtomicInteger getOnlineCount() {
        return onlineCount;
    }

    /*
     * @Description: 服务端向客户端推送数据
     * @Method: sendMessage
     * @Param: [message]
     * @Update:
     * @since: 1.0.0
     * @Return: void
     *
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        if (StringUtils.isNotEmpty(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用户" + userId + ",不在线！");
        }
    }

    /*
     * @Description: 在线人数递增
     * @Method: addOnlineCount
     * @Param: []
     * @Update:
     * @since: 1.0.0
     * @Return: void
     *
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount.incrementAndGet();
    }

    /*
     * @Description: 在线人数递减
     * @Method: subOnlineCount
     * @Param: []
     * @Update:
     * @since: 1.0.0
     * @Return: void
     *
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount.decrementAndGet();
    }
}


